package com.heima.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.service.CommentRepayService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {


    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 评论回复功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //   1. 校验参数
        //  评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前  (注解校验)

        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数不能为空");
        }
        if(dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }

        if(dto.getSize()==null||dto.getSize()==0){
            dto.setSize(10);
        }
        //   2. 条件查询评论回复信息
        //	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                .with( Sort.by(Sort.Direction.DESC, "createdTime"))
                .with( PageRequest.of(0,dto.getSize()));
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);

        List<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();

        //  3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //3.1 如果未登录直接 返回评论回复列表
        if (user == null) {
            return ResponseResult.okResult(repayList);
        }
        //	3.2 如果登录，需要判断哪些回复点过赞

        //     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        List<ApCommentRepayLike> repayLikeList = mongoTemplate.findAll(ApCommentRepayLike.class);
        //    遍历 当前回复列表，将每一个回复信息 封装成 vo
        for (ApCommentRepay apCommentRepay : repayList) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
            //   判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            for (ApCommentRepayLike repayLike : repayLikeList) {

                if (apCommentRepay.getAuthorId().equals(user.getId()) && repayLike.getCommentRepayId().equals(apCommentRepay.getId())) {
                    apCommentRepayVO.setOperation((short) 0);
                }

            }
            apCommentRepayVOS.add(apCommentRepayVO);
        }

        return ResponseResult.okResult(apCommentRepayVOS);
    }

    /**
     * 评论回复保存功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        // 1. 参数校验:
        //  是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符(注解校验)
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "参数不能为空");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }
        //  回复内容安全校验
        //    简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        boolean scan = handleTextScan(dto.getContent());
        if (!scan) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "您的回复中包含敏感词");
        }
        //  2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment comment = mongoTemplate.findOne(query, ApComment.class);
        if(comment==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"查询不到这条评论");
        }
        // 3. 保存评论回复信息
        ApCommentRepay apCommentRepay1 = new ApCommentRepay();
        apCommentRepay1.setAuthorId(user.getId());
        apCommentRepay1.setAuthorName(user.getName());
        apCommentRepay1.setContent(dto.getContent());
        apCommentRepay1.setCommentId(dto.getCommentId());
        apCommentRepay1.setLikes(0);
        apCommentRepay1.setCreatedTime(new Date());
        mongoTemplate.save(apCommentRepay1);
        //  4. 修改评论信息中回复数量 + 1
        Query query1 = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query1, ApComment.class);
        Integer reply = apComment.getReply();
        Integer i = reply + 1;
        Update update = new Update();
        update.set("reply", i);
        mongoTemplate.updateMulti(query1, update, ApComment.class);

        return ResponseResult.okResult(apCommentRepay1);
    }

    /**
     * 点赞回复评论功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        // 1. 校验参数   回复id不能为空   operation 必须 0 或 1(注解校验)
        if(dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请传入正确参数");
        }
        //    校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        RLock lock = redissonClient.getLock("likes-lock");
        lock.lock();
        ApCommentRepay commentRepay;
        try {
            //   校验回复信息是否存在
            Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
            commentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);
            if(commentRepay==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"您点赞的内容不存在");
            }

            Query query1 = Query.query(Criteria.where("commentId").is(dto.getCommentRepayId()));
            ApCommentRepayLike repayLike = mongoTemplate.findOne(query1, ApCommentRepayLike.class);

            // 2. 如果是点赞  判断是否点过赞
            if(dto.getOperation()==0){
                //若没有点过赞
                if(repayLike==null) {
                    //  未点过赞， 保存点赞信息
                    ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
                    apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                    apCommentRepayLike.setOperation(dto.getOperation());
                    apCommentRepayLike.setAuthorId(user.getId());
                    mongoTemplate.save(apCommentRepayLike);
                    //    并将回复信息的点赞数量字段+1
                    Integer i = commentRepay.getLikes() + 1;
                    Update update = new Update();
                    update.set("likes",i).set("createdTime",new Date());
                    mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
                    commentRepay.setLikes(i);
                }else {

                    //    点过赞提示请勿重复点赞
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
                }
            }else {
                //   3. 如果是取消赞 删除点赞信息
                mongoTemplate.remove(query1,ApCommentRepayLike.class);

                //将回复信息的点赞数量字段-1
                Integer likes = commentRepay.getLikes();
                if(likes>=1){
                    Integer i = likes - 1;
                    Update update = new Update();
                    update.set("likes",i);
                    mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
                    // 并将回复信息的点赞数量字段
                    commentRepay.setLikes(i);
                }
            }
        } finally {
            lock.unlock();
        }
        //  4. 返回当前回复的最新点赞数量      数据的key:  likes
        Map<String, Object> map = new HashMap<>();
        map.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(map);
    }


    /**
     * 阿里云文本审核
     *
     * @param content
     * @return
     */
    private boolean handleTextScan(String content) {
        boolean flag = true;
        //
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    flag = false;
                    break;
                case "review":
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}", e.getMessage());
        }
        return flag;
    }
}
